<template>
  <div class="profile-container">
    <el-row :gutter="24">
      <!-- 第一行 -->
      <el-col :span="12">
        <el-card class="square-card user-card">
          <template #header>
            <div class="card-header">
              <span>{{ userInfo.nickname || userInfo.username }}</span>
            </div>
          </template>
          <div class="user-info">
            <p class="username">{{ userInfo.nickname || userInfo.username }}</p>
            <p>{{ userInfo.email || '暂无邮箱' }}</p>
            <p>{{ userInfo.phone || '暂无手机号' }}</p>
          </div>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">{{ orderCount }}</div>
              <div class="stat-label">订单数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ addressCount }}</div>
              <div class="stat-label">地址数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">¥{{ balance.toFixed(2) }}</div>
              <div class="stat-label">账户余额</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="square-card profile-card">
          <template #header>
            <div class="card-header">
              <span>个人资料</span>
              <el-button type="primary" size="small" @click="editProfile" style="padding: 6px 12px; font-size: 12px;">编辑</el-button>
            </div>
          </template>
          <div class="profile-content">
            <div class="profile-item">
              <span class="label">用户名:</span>
              <span class="value">{{ userInfo.username }}</span>
            </div>
            <div class="profile-item">
              <span class="label">昵称:</span>
              <span class="value">{{ userInfo.nickname || '未设置' }}</span>
            </div>
            <div class="profile-item">
              <span class="label">手机号:</span>
              <span class="value">{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="profile-item">
              <span class="label">邮箱:</span>
              <span class="value">{{ userInfo.email || '未设置' }}</span>
            </div>
            <div class="profile-item">
              <span class="label">性别:</span>
              <span class="value">{{ getGenderText(userInfo.gender) }}</span>
            </div>
            <div class="profile-item">
              <span class="label">生日:</span>
              <span class="value">{{ userInfo.birthday || '未设置' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 第二行 -->
      <el-col :span="12">
        <el-card class="square-card balance-card">
          <template #header>
            <div class="card-header">
              <span>余额管理</span>
            </div>
          </template>
          <div class="balance-content" v-loading="balanceLoading">
            <div class="balance-amount">
              <h2>¥{{ balance.toFixed(2) }}</h2>
            </div>
            <div class="balance-actions">
              <el-button type="primary" size="small" @click="showRechargeDialog" style="padding: 8px 15px; font-size: 13px;">充值</el-button>
              <el-button type="warning" size="small" @click="showWithdrawDialog" style="padding: 8px 15px; font-size: 13px;">提现</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="square-card security-card">
          <template #header>
            <div class="card-header">
              <span>账号安全</span>
            </div>
          </template>
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">登录密码</div>
                <div class="security-desc">定期修改密码可以保护账号安全</div>
              </div>
              <el-button type="primary" link @click="changePassword" style="font-size: 12px; padding: 0;">修改</el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">手机绑定</div>
                <div class="security-desc">{{ userInfo.phone ? `已绑定手机号: ${userInfo.phone}` : '未绑定手机号' }}</div>
              </div>
              <el-button type="primary" link @click="bindPhone" style="font-size: 12px; padding: 0;">{{ userInfo.phone ? '修改' : '绑定' }}</el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">邮箱绑定</div>
                <div class="security-desc">{{ userInfo.email ? `已绑定邮箱: ${userInfo.email}` : '未绑定邮箱' }}</div>
              </div>
              <el-button type="primary" link @click="bindEmail" style="font-size: 12px; padding: 0;">{{ userInfo.email ? '修改' : '绑定' }}</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑个人资料对话框 -->
    <el-dialog
      v-model="profileDialogVisible"
      title="编辑个人资料"
      width="500px"
    >
      <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="100px">
        <!-- 移除头像上传组件 -->

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="profileForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="0">保密</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="生日">
          <el-date-picker
            v-model="profileForm.birthday"
            type="date"
            placeholder="选择生日"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="profileDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProfile">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" show-password />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePassword">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改手机号对话框 -->
    <el-dialog
      v-model="phoneDialogVisible"
      title="修改手机号"
      width="500px"
    >
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" label-width="100px">
        <el-form-item label="当前手机号">
          <el-input :value="userInfo.phone || '未绑定'" disabled />
        </el-form-item>

        <el-form-item label="新手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入新手机号" />
        </el-form-item>

        <el-form-item label="当前密码" prop="password">
          <el-input v-model="phoneForm.password" type="password" placeholder="请输入当前密码验证身份" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="phoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePhone">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改邮箱对话框 -->
    <el-dialog
      v-model="emailDialogVisible"
      title="修改邮箱"
      width="500px"
    >
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="100px">
        <el-form-item label="当前邮箱">
          <el-input :value="userInfo.email || '未绑定'" disabled />
        </el-form-item>

        <el-form-item label="新邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入新邮箱" />
        </el-form-item>

        <el-form-item label="当前密码" prop="password">
          <el-input v-model="emailForm.password" type="password" placeholder="请输入当前密码验证身份" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="emailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEmail">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog
      title="充值"
      v-model="rechargeDialogVisible"
      width="30%"
    >
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="80px">
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model.number="rechargeForm.amount" type="number" min="0.01" placeholder="请输入充值金额">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="rechargeForm.remark" placeholder="请输入备注（选填）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge" :loading="submitting">确认充值</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提现对话框 -->
    <el-dialog
      title="提现"
      v-model="withdrawDialogVisible"
      width="30%"
    >
      <el-form :model="withdrawForm" :rules="withdrawRules" ref="withdrawFormRef" label-width="80px">
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model.number="withdrawForm.amount" type="number" min="0.01" :max="balance" placeholder="请输入提现金额">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="withdrawForm.remark" placeholder="请输入备注（选填）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWithdraw" :loading="submitting">确认提现</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
// 移除不需要的图标导入
import type { FormInstance } from 'element-plus'
import { getOrders, getAddresses, updatePassword, updateUserInfo, getUserBalance, operateBalance } from '@/api/user'

const userStore = useUserStore()

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 订单数和地址数
const orderCount = ref(0)
const addressCount = ref(0)

// 余额数据
const balance = ref(0)
const balanceLoading = ref(false)

// 充值相关
const rechargeDialogVisible = ref(false)
const rechargeForm = ref({
  amount: '',
  remark: '',
  type: 1 // 1-充值
})
const rechargeFormRef = ref<FormInstance>()
const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
}

// 提现相关
const withdrawDialogVisible = ref(false)
const withdrawForm = ref({
  amount: '',
  remark: '',
  type: 2 // 2-提现
})
const withdrawFormRef = ref<FormInstance>()
const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > balance.value) {
          callback(new Error('提现金额不能大于余额'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const submitting = ref(false)

// 编辑个人资料对话框
const profileDialogVisible = ref(false)
const profileFormRef = ref<FormInstance>()
const profileForm = ref({
  nickname: '',
  phone: '',
  email: '',
  gender: 0,
  birthday: ''
})

// 个人资料表单验证规则
const profileRules = {
  nickname: [
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 修改手机号对话框
const phoneDialogVisible = ref(false)
const phoneFormRef = ref<FormInstance>()
const phoneForm = ref({
  phone: '',
  password: ''
})

// 手机号表单验证规则
const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入当前密码验证身份', trigger: 'blur' }
  ]
}

// 修改邮箱对话框
const emailDialogVisible = ref(false)
const emailFormRef = ref<FormInstance>()
const emailForm = ref({
  email: '',
  password: ''
})

// 邮箱表单验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入当前密码验证身份', trigger: 'blur' }
  ]
}

// 获取用户余额
const fetchUserBalance = async () => {
  balanceLoading.value = true
  try {
    const response = await getUserBalance()
    if (response.code === 200) {
      balance.value = response.data.balance
    }
  } catch (error) {
    console.error('获取余额失败:', error)
    ElMessage.error('获取余额失败')
  } finally {
    balanceLoading.value = false
  }
}

// 显示充值对话框
const showRechargeDialog = () => {
  rechargeForm.value = {
    amount: '',
    remark: '',
    type: 1
  }
  rechargeDialogVisible.value = true
}

// 显示提现对话框
const showWithdrawDialog = () => {
  withdrawForm.value = {
    amount: '',
    remark: '',
    type: 2
  }
  withdrawDialogVisible.value = true
}

// 处理充值
const handleRecharge = async () => {
  if (!rechargeFormRef.value) return

  await rechargeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const response = await operateBalance(rechargeForm.value)
        if (response.code === 200) {
          ElMessage.success('充值成功')
          rechargeDialogVisible.value = false
          balance.value = response.data.balance
        } else {
          ElMessage.error(response.message || '充值失败')
        }
      } catch (error) {
        console.error('充值失败:', error)
        ElMessage.error('充值失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 处理提现
const handleWithdraw = async () => {
  if (!withdrawFormRef.value) return

  await withdrawFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const response = await operateBalance(withdrawForm.value)
        if (response.code === 200) {
          ElMessage.success('提现成功')
          withdrawDialogVisible.value = false
          balance.value = response.data.balance
        } else {
          ElMessage.error(response.message || '提现失败')
        }
      } catch (error) {
        console.error('提现失败:', error)
        ElMessage.error('提现失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 获取用户信息、订单数和地址数
onMounted(async () => {
  if (Object.keys(userInfo.value).length === 0) {
    await userStore.getUserInfo()
  }

  // 获取实际的订单数和地址数
  try {
    const ordersResponse = await getOrders()
    if (ordersResponse.code === 200) {
      // 订单数据是分页对象，总数在total属性中
      orderCount.value = ordersResponse.data.total || 0
    }

    const addressesResponse = await getAddresses()
    if (addressesResponse.code === 200) {
      addressCount.value = addressesResponse.data.length
    }

    // 获取用户余额
    await fetchUserBalance()
  } catch (error) {
    console.error('获取订单或地址数据失败:', error)
  }
})

// 获取性别文本
const getGenderText = (gender) => {
  const genderMap = {
    0: '保密',
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '保密'
}

// 编辑个人资料
const editProfile = () => {
  profileForm.value = {
    nickname: userInfo.value.nickname || '',
    phone: userInfo.value.phone || '',
    email: userInfo.value.email || '',
    gender: userInfo.value.gender || 0,
    birthday: userInfo.value.birthday || ''
  }

  profileDialogVisible.value = true
}

// 移除头像上传处理函数

// 保存个人资料
const saveProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用API保存个人资料
        const response = await updateUserInfo(profileForm.value)

        if (response.code === 200) {
          ElMessage.success('保存成功')
          profileDialogVisible.value = false

          // 更新本地用户信息
          userStore.userInfo = response.data
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        console.error('保存个人资料失败:', error)
        ElMessage.error('保存个人资料失败，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 修改密码
const changePassword = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }

  passwordDialogVisible.value = true
}

// 保存密码
const savePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用API修改密码
        const response = await updatePassword({
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        })

        if (response.code === 200) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 绑定手机
const bindPhone = () => {
  phoneDialogVisible.value = true
}

// 绑定邮箱
const bindEmail = () => {
  emailDialogVisible.value = true
}

// 保存手机号
const savePhone = async () => {
  if (!phoneFormRef.value) return

  await phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用API修改手机号
        const response = await updateUserInfo({
          phone: phoneForm.value.phone
        }) as any

        if (response.code === 200) {
          ElMessage.success('手机号修改成功')
          phoneDialogVisible.value = false

          // 更新本地用户信息
          userStore.userInfo = response.data
        } else {
          ElMessage.error(response.message || '手机号修改失败')
        }
      } catch (error) {
        console.error('修改手机号失败:', error)
        ElMessage.error('修改手机号失败，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 保存邮箱
const saveEmail = async () => {
  if (!emailFormRef.value) return

  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用API修改邮箱
        const response = await updateUserInfo({
          email: emailForm.value.email
        }) as any

        if (response.code === 200) {
          ElMessage.success('邮箱修改成功')
          emailDialogVisible.value = false

          // 更新本地用户信息
          userStore.userInfo = response.data
        } else {
          ElMessage.error(response.message || '邮箱修改失败')
        }
      } catch (error) {
        console.error('修改邮箱失败:', error)
        ElMessage.error('修改邮箱失败，请稍后重试')
      }
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

/* 正方形卡片样式 */
.square-card {
  height: 380px;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.square-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
  padding: 12px 20px !important;
  border-bottom: 1px solid #ebeef5;
}

/* 用户卡片样式 */
.user-card {
  text-align: center;
}

.user-info {
  padding: 20px 0;
}

.user-info .username {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.user-info p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 13px;
  color: #606266;
}

/* 个人资料卡片样式 */
.profile-content {
  padding: 15px;
  height: calc(100% - 50px);
  overflow-y: auto;
}

.profile-item {
  display: flex;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #ebeef5;
}

.profile-item .label {
  width: 70px;
  color: #606266;
  font-weight: 500;
  font-size: 13px;
}

.profile-item .value {
  flex: 1;
  color: #333;
  font-size: 13px;
}

/* 余额卡片样式 */
.balance-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: calc(100% - 50px);
  padding: 20px;
}

.balance-amount {
  margin-bottom: 30px;
}

.balance-amount h2 {
  font-size: 36px;
  color: #409EFF;
  margin: 0;
}

.balance-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 安全卡片样式 */
.security-items {
  padding: 10px;
  height: calc(100% - 50px);
  overflow-y: auto;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.security-item:last-child {
  border-bottom: none;
}

.security-title {
  font-size: 14px;
  margin-bottom: 4px;
  color: #303133;
}

.security-desc {
  font-size: 12px;
  color: #909399;
  max-width: 220px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
